package domain;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Writable;
import org.json.JSONException;
import org.json.JSONObject;

public class Tweet implements Writable{
	
	private static Tweet instance;
	private User user;
	private String text;

	//singleton Tweet instance
	static synchronized public Tweet getInstance(){
		if(instance == null){
			return new Tweet();
		}else{
			return instance;
		}
	}	
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	@Override
	public void readFields(DataInput arg0) throws IOException {
		parseTweetFromString(arg0.toString());
	}

	@Override
	public void write(DataOutput arg0) throws IOException {
		arg0.writeUTF(Tweet.getInstance().toString());
	}

	
	@Override
	public String toString(){
		return Tweet.getInstance().getUser().toString() + " - " + Tweet.getInstance().getText();
	}
	
	public Tweet parseTweetFromString(String data) {
		Tweet single_tweet = Tweet.getInstance(); 
		JSONObject myjSON;
 		try {
			myjSON = new JSONObject(data);
			single_tweet.setUser(User.parseUserFromString(data));
 			if(myjSON.has("text")){
				single_tweet.setText(myjSON.getString("text"));		
 			}else{	
				single_tweet.setText("no text");
				//throw new JSONException("Text not available");  		
 			}				
 		} catch (JSONException e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}
		return single_tweet;
 	}

}

